package com.worthtech.billportal.dao.hibernate;

import java.util.List;

import com.worthtech.billportal.bean.WlExpressInfo;
import com.worthtech.billportal.bean.WlId;
import com.worthtech.billportal.dao.ExpressDAO;
import com.worthtech.billportal.util.AbstractManager;
import com.worthtech.billportal.util.Util;

public class ExpressHibernateDAO extends AbstractManager implements ExpressDAO{
	public List getListByHQL(String tableName, int startPage, int perNo,
			String orderby) {
		String hql = "from " + tableName + " " + orderby;
		System.out.println("hql2=" + hql);
		if(perNo==0){
			List l = this.getHibernateTemplate().find(hql);
			System.out.println("size = "+l.size());
			return l;
		}
		return this.getSession().createQuery(hql).setFirstResult(startPage)
				.setMaxResults(perNo).list();
	}
	public String getCount(String tableName, String condition) {
		String hql = "select count(*) from " + tableName + " " + condition;
		System.out.println("hql1=" + hql);
		String tmp = this.getSession().createQuery(hql).list().get(0)
				.toString();
		System.out.println("count=" + tmp);
		return tmp;
	}
	
	public String getExpressID(){
		List l = this.getHibernateTemplate().find("from WlId");
		if(l.size()>0){
			WlId w = (WlId)l.get(0);
			System.out.println(w.getExpressId()+" "+w.getExpressDate());
			if(!w.getExpressDate().equals(Util.getCurrentDayID())){
				w.setExpressId(Long.valueOf(1));
				w.setExpressDate(Util.getCurrentDayID());
				this.update(w);
				return Util.getCurrentDayID()+"000001";
			}else{
				long id =w.getExpressId()+1;
				w.setExpressId(id);
				this.update(w);
				return w.getExpressDate()+Util.addZero(id+"", 6);
			}
		}else{
			WlId w = new WlId();
			w.setExpressDate(Util.getCurrentDayID());
			w.setExpressId(Long.valueOf(1));
			w.setExpressIndex(Long.valueOf(1));
			this.save(w);
			return Util.getCurrentDayID()+"000001";
		}
	}
	public void save(WlExpressInfo w){
		this.getHibernateTemplate().save(w);
	}
	public void update(WlExpressInfo w){
		this.getHibernateTemplate().update(w);
	}
	public String getSeqID(String tablename){
		String tmp =this.getSession().createSQLQuery("SELECT "+tablename+".NEXTVAL FROM dual").list().get(0).toString();
		return tmp;
	}
}
